package com.bz.security;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import com.bz.common.Codeenum;
import com.bz.common.CommonHeader;
import com.bz.common.ResponseDto;
import com.bz.common.ResponseUtils;
import com.bz.common.UserConfig;
import com.bz.entity.UserEntity;
import com.bz.model.RoleUrlDto;
import com.bz.model.UrlFilter;

@Component
public class AuthInfoInterceptor implements HandlerInterceptor {

    @Autowired
    private UrlFilter urls;

    @Value("${spring.jmx.default-domain}")
    private String    projectName;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String username = request.getHeader("username");
        CommonHeader ch = new CommonHeader();
        ch.setUsername(username);

        // 直接搂下来，放到ThreadLocal中 后续直接从中获取
        ThreadLocalUtils.set(ch);

        String url = request.getRequestURI();
        UserEntity user = UserConfig.getLoginUser();
        if (!checkRight(user, url)) {

            // 未登录，返回登陆页
            ResponseUtils.setResponse(response, new ResponseDto<>(Codeenum.NOT_RIGHT));
            return false;
        }

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        // 移除app-user
        ThreadLocalUtils.remove();
    }

    /**
     * 权限校验
     * 
     * @param user
     * @param url
     * @return
     */
    private boolean checkRight(UserEntity user, String url) {
        if (StringUtils.equals("/" + projectName + "/error", url)) {
            return true;
        }
        AntPathMatcher mather = new AntPathMatcher();
        if ((!CollectionUtils.isEmpty(urls.getUrls()))) {
            for (String u : urls.getUrls()) {
                if (mather.match("/" + projectName + u, url)) {
                    return true;
                }
            }
        }

        if (null == user || StringUtils.isEmpty(url)) {
            return false;
        }
        List<RoleUrlDto> urls = user.getUrls();
        if (CollectionUtils.isEmpty(urls)) {
            return false;
        }
        for (RoleUrlDto u : urls) {
            String rurl = null;
            if (u.getUrl().startsWith("/")) {
                rurl = "/" + projectName + u.getUrl();
            } else {
                rurl = "/" + projectName + "/" + u.getUrl();
            }
            if (StringUtils.equals(rurl, url)) {
                return true;
            }
        }
        return false;
    }
}
